﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Text;
using _18miljard.Mail;

namespace _18miljard.TextLinks
{
	public class TextLinkCollector : XmlDocument
	{
		TextLinkCollection textLinks = new TextLinkCollection();
		DateTime now = DateTime.Today; //must be property, since the class is cached.
		bool checkExpired;

		public TextLinkCollector()
			: this(false)
		{
		}

		public TextLinkCollector(bool checkExpired)
		{
			this.checkExpired = checkExpired;
			this.ReadTextLinks();
		}

		private void ReadTextLinks()
		{
			string path = HttpContext.Current.Server.MapPath("/App_Data/TextLinks.xml");

			this.Load(path);

			XmlNodeList nodes = this.SelectNodes("/miljard/links/link");

			foreach (XmlNode node in nodes)
			{
				this.ReadTextLink(node);
			}

			this.RemoveAll();
		}

		private void ReadTextLink(XmlNode node)
		{
			bool isOneDayExpired = false;
			bool expiresInSevenDays = false;

			XmlAttribute attrStartDate = node.Attributes["startdate"];
			XmlAttribute attrEndDate = node.Attributes["enddate"];

			if (attrStartDate == null || attrEndDate == null)
				return;

			DateTime startDate = DateTime.Parse(attrStartDate.Value);
			DateTime endDate = DateTime.Parse(attrEndDate.Value);

			if (startDate > this.now || endDate <= this.now)
			{
				isOneDayExpired = this.checkExpired && (endDate == this.now);

				if (isOneDayExpired == false)
					return;
			}
			else
			{
				expiresInSevenDays = this.checkExpired && (endDate.Subtract(this.now).Days == 7);
			}


			string href = null;
			string text = null;
			string prefix = null;
			string suffix = null;

			string name = null;
			string email = null;

			bool nofollow = false;

			bool frontpageonly = false;

			if (isOneDayExpired || expiresInSevenDays)
			{
				XmlAttribute attrName = node.Attributes["name"];
				XmlAttribute attrEmail = node.Attributes["email"];

				if (attrName != null)
					name = attrName.Value;

				if (attrEmail != null)
					email = attrEmail.Value;
			}

			foreach (XmlNode childNode in node.ChildNodes)
			{
				switch (childNode.LocalName)
				{
					case "href":
						XmlAttribute hrefAttr = childNode.Attributes["url"];
						if (hrefAttr != null)
							href = hrefAttr.Value;

						XmlAttribute textAttr = childNode.Attributes["text"];
						if (textAttr != null)
							text = textAttr.Value;

						XmlAttribute prefixAttr = childNode.Attributes["prefix"];
						if (prefixAttr != null)
							prefix = prefixAttr.Value;

						XmlAttribute suffixAttr = childNode.Attributes["suffix"];
						if (suffixAttr != null)
							suffix = suffixAttr.Value;

						XmlAttribute frontpageonlyAttr = childNode.Attributes["frontpageonly"];
						if (frontpageonlyAttr != null)
							frontpageonly = XmlConvert.ToBoolean(frontpageonlyAttr.Value);

						XmlAttribute nofollowAttr = childNode.Attributes["nofollow"];
						if (nofollowAttr != null)
							nofollow = XmlConvert.ToBoolean(nofollowAttr.Value);

						break;
				}
			}

			if (href != null && text != null)
			{
				TextLink textLink = new TextLink(href, text, prefix, suffix, name, email, frontpageonly, nofollow);

				if (isOneDayExpired || expiresInSevenDays)
				{
					this.NotifyAdvertiser(textLink, startDate, endDate, isOneDayExpired);
				}
				else
				{
					this.TextLinks.Add(textLink);
				}
			}
		}

		private void NotifyAdvertiser(TextLink textLink, DateTime startDate, DateTime endDate, bool expired)
		{
			MailArguments mailArgs = MailArguments.MailArgs;
			mailArgs.Clear();

			StringBuilder str = new StringBuilder(128);
			if (textLink.Prefix != null)
			{
				str.Append(textLink.Prefix);
				str.Append(" ");
			}

			str.Append(textLink.Text);

			if (textLink.Suffix != null)
			{
				str.Append(" ");
				str.Append(textLink.Suffix);
			}

			mailArgs["{aanhef}"] = "Geachte " + textLink.Name + ",";
			mailArgs["{startdate}"] = startDate.ToLongDateString();
			mailArgs["{enddate}"] = endDate.ToLongDateString();
			mailArgs["{text}"] = str.ToString();
			mailArgs["{link}"] = textLink.Href;

			EMail email = MailCache.GetMail(expired ? "textadexpired" : "textadexpiresinsevendays");
			email.Recipients = textLink.Email;

			email.QueueSingle();
		}

		public TextLinkCollection TextLinks
		{
			get { return this.textLinks; }
		}
	}
}
